package com.kexio.core.web.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kexio.common.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应包装器
 * 自动将Controller返回值包装为Result格式
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@RestControllerAdvice
public class ResponseWrapper implements ResponseBodyAdvice<Object> {
    
    private static final Logger log = LoggerFactory.getLogger(ResponseWrapper.class);
    
    private final ObjectMapper objectMapper;
    
    public ResponseWrapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查是否需要包装响应
        String packageName = returnType.getDeclaringClass().getPackage().getName();
        
        // 跳过Spring Boot Actuator和Swagger相关的响应
        if (packageName.startsWith("org.springframework.boot.actuator") ||
            packageName.startsWith("org.springdoc") ||
            packageName.startsWith("springfox.documentation")) {
            return false;
        }
        
        // 跳过错误处理器的响应
        if (packageName.contains("error") || packageName.contains("exception")) {
            return false;
        }
        
        // 如果返回类型已经是Result，则不需要再包装
        if (returnType.getParameterType().equals(Result.class)) {
            return false;
        }
        
        return true;
    }
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                ServerHttpRequest request, ServerHttpResponse response) {
        
        // 如果body已经是Result类型，直接返回
        if (body instanceof Result) {
            return body;
        }
        
        // 包装成Result对象
        Result<Object> result = Result.success(body);
        
        // 处理String类型的特殊情况，避免类型转换异常
        if (returnType.getParameterType().equals(String.class)) {
            try {
                return objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                log.error("JSON序列化失败", e);
                return Result.error("响应序列化失败");
            }
        }
        
        return result;
    }
}
